package com.tianji.learning.task;

import com.tianji.learning.service.IPointsBoardSeasonService;
import com.tianji.learning.service.impl.PointsBoardServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@RequiredArgsConstructor
public class ListenBoardExpire {
    private final StringRedisTemplate redisTemplate;
    private final IPointsBoardSeasonService pointsBoardSeasonService;
    private final PointsBoardServiceImpl pointsBoardService;


    /*@Scheduled(cron = "0 0 0 1 * ?")//每月1号0点执行
    public void Listen(){
        //1.获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //1.1 获取一个月前的时间
        LocalDateTime beforeOneMonth=now.minusMonths(1);
        //2.格式化时间为yyyyMMM
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyyMMM");
        String format = beforeOneMonth.format(timeFormatter);
        //3.查询赛季表获得该赛季id
        //3.1 获取上个月的开始时间
        LocalDateTime beginTime = beforeOneMonth.withDayOfMonth(1);
        //3.2 格式化时间为yyyyMMdd
        String seasonBeginTime = beginTime.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        PointsBoardSeason season = pointsBoardSeasonService.lambdaQuery().eq(PointsBoardSeason::getBeginTime, seasonBeginTime).one();
        //4.拼接上个月的key
        String key= RedisConstants.POINTS_KEY_PREFIX+format;
        //5.读取上个月的redis数据
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet().reverseRangeWithScores(key, 0, -1);
        if (CollUtil.isEmpty(typedTuples)){
            return;
        }
        int count=1;
        ArrayList<PointsBoard> list = new ArrayList<>(typedTuples.size());
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            String userIdStr = tuple.getValue();
            PointsBoard board = new PointsBoard();
            if (userIdStr!=null){
                board.setUserId(Long.valueOf(userIdStr));
            }
            board.setPoints( tuple.getScore().intValue());
            board.setSeason(season.getId());
            board.setRank(count);
            count++;
            list.add(board);
        }
        //6.将上个月的redis数据持久化到db中
        pointsBoardService.saveBatch(list);
        //7.删除上个月的redis数据
        redisTemplate.delete(key);
    }*/
}
